﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Reflection;

namespace TWiStEr.ANSIVT100Colorizer {
	class Program {
		static void Main(string[] args) {
			string line = null;
			FieldInfo _outField = Console.Out.GetType().GetField("_out", BindingFlags.NonPublic | BindingFlags.Instance);
			((StreamWriter)_outField.GetValue(Console.Out)).AutoFlush = false;
			while ((line = Console.ReadLine()) != null) {
				if (!line.Contains((char)27)) {
					Console.WriteLine(line);
					continue;
				}
				Process(line);
			}
		}

		static ConsoleColor[] colorMap = { 
              ConsoleColor.Black,
              ConsoleColor.Red,
              ConsoleColor.Green,
              ConsoleColor.Yellow,
              ConsoleColor.Blue,
              ConsoleColor.Magenta,
              ConsoleColor.Cyan, 
              ConsoleColor.White };
		static ConsoleColor[] colorMapDark = { 
              ConsoleColor.Black,
              ConsoleColor.DarkRed,
              ConsoleColor.DarkGreen,
              ConsoleColor.DarkYellow,
              ConsoleColor.DarkBlue,
              ConsoleColor.DarkMagenta,
              ConsoleColor.DarkCyan, 
              ConsoleColor.Gray };

		private static void Process(string line) {
			ConsoleColor[] colors = colorMap;
			for (int i = 0; i < line.Length; ++i) {
				if (line[i] == 27
					&& i + 1 < line.Length
					&& line[i + 1] == '[') {
					i += 2;
					if (i >= line.Length) break;
					if (line[i] == '1') {
						colors = colorMap; // bright
						i++; // jump to next
						i++; // skip ; or m
					} else if (line[i] == '2') {
						colors = colorMapDark; // dim
						i++; // jump to next
						i++; // skip ; or m
					}
					if (line[i] == '3') {
						Console.Out.Flush();
						Console.ForegroundColor = colors[line[++i] - '0'];
						i++; // skip m
					} else if (line[i] == '4') {
						Console.Out.Flush();
						Console.BackgroundColor = colors[line[++i] - '0'];
						i++; // skip m
					} else if (line[i] == '0' || line[i] == 'm') {
						Console.Out.Flush();
						Console.ResetColor();
					} else {
						Console.Write(line[i]);
					}
				} else {
					Console.Write(line[i]);
				}
			}
			Console.WriteLine();
			Console.Out.Flush();
		}
	}
}
